#============================================================
# Create Time:			2021-11-02 08:56:58
# Last modify:			2021-11-02 07:08:30
# Writer:				Wenhao	wh.wenhao@foxmail.com
# File Name:			utils.py
# File Type:			PY Source File
# Tool:					Mac -- vim & python
# Information:			
#============================================================
import struct

def send_data(tcp_socket, string: str):
    # 将待发送文本数据转化为字节码
    content = string.encode('utf-8')
    size = len(content)
    # 用四个字节表示待发送正文的长度
    size_content = struct.pack('!I', size)
    # 基于TCP，发送数据
    tcp_socket.sendall(size_content + content)
    print('Send successfully!')

def recv_data(tcp_socket)->str:
    # 先从tcp socket中读取四个字节，以获取待传输正文字节码的长度
    size = tcp_socket.recv(4)
    if not size:
        return ''
    size = struct.unpack('!I', size)[0]
    # 按照已经获得的正文长度，读取正文数据
    content = tcp_socket.recv(size)
    return content.decode('utf-8') # 将正文的字节码数据转化为字符串.
